#!/bin/sh

if [ -z "$1" ]
then
	echo "Usage: reccap-start FILENAME [fps=24] [ffmpeg/acvonv] [pusle/alsa] [X,Y] [WIDTHxHEIGHT]"
	exit 1
elif [ -e "$1" ]
then
	reccap-kill "$1"
fi

capper="$3"
if [ -z "$capper" ]
then
	ffmpeg="ffmpeg"
	avconv="avconv"
	if [ ! -z "$(which $ffmpeg)" ]
	then
		capper=$ffmpeg
	elif [ ! -z "$(which $avconv)" ]
	then
		capper="$avconv"
	fi

	if [ -z "$capper" ]
	then
		echo Install ffmpeg or avconv!
		exit 1
	fi
elif [ -z $(which "$capper") ]
then
	echo "$capper" does not seem to be a valid command
	exit 1
fi

slop="slop"
if [ -z "$(which $slop)" ]
then
	echo Install slop!
	exit 1
fi

framerate="$2"
if [ -z "$framerate" ]
then
	framerate="24"
fi

audio_params=""
if [ ! -z "$4" ]
then
	audio_params="-f $4 -i default"
fi

get_position()
{
	echo "$3,$4"
}

get_size()
{
	echo "$1x$2"
}

if [ -z "$5" ] || [ -z "$6" ]
then
	geometry=$("$slop" -b 1 -f %g 2> /dev/null | sed "s/[^0-9]/ /g")
	position=$(get_position $geometry)
	size=$(get_size $geometry)
fi

if [ ! -z "$5" ]
then
	position="$5"
fi

if [ ! -z "$6" ]
then
	size="$6"
fi

yes | $capper -video_size "$size" -framerate "$framerate" -f x11grab -i :0.0+"$position" $audio_params -crf 0 -preset ultrafast "$1" 2> /dev/null > /dev/null &
